/****************************************************************************
 *
 *   Copyright (c) 2019 PX4 Development Team. All rights reserved.
 *   Copyright (c) 2025 H743 Flight Controller Project. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

#include <px4_platform_common/px4_work_queue/work_queue_manager.hpp>
#include <px4_platform_common/px4_work_queue/work_queue.hpp>
#include <px4_platform_common/atomic.hpp>
#include <px4_platform_common/containers/blocking_list.hpp>
#include <px4_platform_common/containers/blocking_queue.hpp>

#include "FreeRTOS.h"
#include "task.h"

#include <string.h>

// Forward declaration of debug_printf from main.c
extern "C" int debug_printf(const char *format, ...);

namespace px4
{

// List of current work queues
static BlockingListTemplate<WorkQueue *> *_wq_manager_wqs_list{nullptr};

// Queue of WorkQueues to be created (as threads in the wq manager task)
static BlockingQueue<const wq_config_t *, 1> *_wq_manager_create_queue{nullptr};

// Manager task handle
static TaskHandle_t _wq_manager_task_handle{nullptr};

// Atomic flags for manager state
static px4::atomic_bool _wq_manager_should_exit{true};
static px4::atomic_bool _wq_manager_running{false};

/**
 * Find a work queue by name
 */
static WorkQueue *FindWorkQueueByName(const char *name)
{
	if (!_wq_manager_running.load()) {
		debug_printf("[WQM] ERROR: not running\n");
		return nullptr;
	}

	LockGuard lg{_wq_manager_wqs_list->mutex()};

	// Search list
	for (WorkQueue *wq : *_wq_manager_wqs_list) {
		if (strcmp(wq->get_name(), name) == 0) {
			return wq;
		}
	}

	return nullptr;
}

/**
 * Find or create a work queue
 */
WorkQueue *WorkQueueFindOrCreate(const wq_config_t &new_wq)
{
	if (!_wq_manager_running.load()) {
		debug_printf("[WQM] ERROR: not running\n");
		return nullptr;
	}

	// Search list for existing work queue
	WorkQueue *wq = FindWorkQueueByName(new_wq.name);

	// Create work queue if it doesn't already exist
	if (wq == nullptr) {
		// Add WQ config to create queue
		// Main thread wakes up, creates the thread
		_wq_manager_create_queue->push(&new_wq);

		// Wait until new wq is created, then return
		uint32_t timeout_ms = 10000; // 10 seconds
		uint32_t elapsed_ms = 0;

		while (wq == nullptr && elapsed_ms < timeout_ms) {
			// Wait 1 ms, checking every iteration
			vTaskDelay(pdMS_TO_TICKS(1));
			elapsed_ms += 1;

			wq = FindWorkQueueByName(new_wq.name);
		}

		if (wq == nullptr) {
			debug_printf("[WQM] ERROR: failed to create %s\n", new_wq.name);
		}
	}

	return wq;
}

/**
 * Map device bus to work queue configuration
 */
const wq_config_t &device_bus_to_wq(uint8_t bus_type, uint8_t bus)
{
	// Bus type: 0=Unknown, 1=I2C, 2=SPI, 3=UAVCAN, 4=Simulation
	if (bus_type == 2) { // SPI
		switch (bus) {
		case 0: return wq_configurations::SPI0;
		case 1: return wq_configurations::SPI1;
		case 2: return wq_configurations::SPI2;
		case 3: return wq_configurations::SPI3;
		case 4: return wq_configurations::SPI4;
		case 5: return wq_configurations::SPI5;
		case 6: return wq_configurations::SPI6;
		}

	} else if (bus_type == 1) { // I2C
		switch (bus) {
		case 0: return wq_configurations::I2C0;
		case 1: return wq_configurations::I2C1;
		case 2: return wq_configurations::I2C2;
		case 3: return wq_configurations::I2C3;
		case 4: return wq_configurations::I2C4;
		}
	}

	// Otherwise use high priority default
	return wq_configurations::hp_default;
}

/**
 * Work queue runner task function
 * Each work queue runs in its own FreeRTOS task
 */
static void WorkQueueRunner(void *context)
{
	wq_config_t *config = static_cast<wq_config_t *>(context);
	WorkQueue wq(*config);

	debug_printf("[WQM] Starting work queue: %s\n", config->name);

	// Add to work queue list
	_wq_manager_wqs_list->add(&wq);

	// Run the work queue (blocks until requested to stop)
	wq.Run();

	// Remove from work queue list
	_wq_manager_wqs_list->remove(&wq);

	debug_printf("[WQM] Work queue stopped: %s\n", config->name);

	// Delete task
	vTaskDelete(nullptr);
}

/**
 * Work queue manager main task
 */
static void WorkQueueManagerRun(void *arg)
{
	(void)arg;

	debug_printf("[WQM] Manager task started\n");

	// Create work queue list and create queue
	_wq_manager_wqs_list = new BlockingListTemplate<WorkQueue *>();
	_wq_manager_create_queue = new BlockingQueue<const wq_config_t *, 1>();

	_wq_manager_running.store(true);

	while (!_wq_manager_should_exit.load()) {
		// Wait for work queue creation requests
		const wq_config_t *wq = _wq_manager_create_queue->pop();

		if (wq != nullptr) {
			// Create new work queue task

			// Calculate priority
			// FreeRTOS priority: 0 = lowest, configMAX_PRIORITIES-1 = highest
			// relative_priority: 0 = highest, negative = lower
			UBaseType_t priority = configMAX_PRIORITIES - 1 + wq->relative_priority;
			if (priority >= configMAX_PRIORITIES) {
				priority = configMAX_PRIORITIES - 1;
			}
			if (priority < 1) {
				priority = 1;
			}

			// Create task
			BaseType_t ret = xTaskCreate(
				WorkQueueRunner,
				wq->name,
				wq->stacksize / sizeof(StackType_t),
				(void *)wq,
				priority,
				nullptr
			);

			if (ret == pdPASS) {
				debug_printf("[WQM] Created work queue: %s (priority=%u, stack=%u)\n",
					wq->name, (unsigned)priority, (unsigned)wq->stacksize);
			} else {
				debug_printf("[WQM] ERROR: Failed to create work queue: %s\n", wq->name);
			}
		}
	}

	_wq_manager_running.store(false);

	debug_printf("[WQM] Manager task stopped\n");

	// Delete task
	vTaskDelete(nullptr);
}

/**
 * Start the work queue manager
 */
int WorkQueueManagerStart()
{
	if (_wq_manager_should_exit.load() && !_wq_manager_running.load()) {

		_wq_manager_should_exit.store(false);

		// Create manager task with highest priority
		BaseType_t ret = xTaskCreate(
			WorkQueueManagerRun,
			"wq:manager",
			1280 / sizeof(StackType_t),
			nullptr,
			configMAX_PRIORITIES - 1,
			&_wq_manager_task_handle
		);

		if (ret != pdPASS) {
			_wq_manager_should_exit.store(true);
			debug_printf("[WQM] ERROR: Failed to create manager task\n");
			return -1;
		}

		// Wait until initialized
		int max_tries = 1000;
		while (!_wq_manager_running.load() && --max_tries > 0) {
			vTaskDelay(pdMS_TO_TICKS(1));
		}

		if (max_tries <= 0) {
			debug_printf("[WQM] ERROR: Failed to wait for manager task to start\n");
			return -1;
		}

		debug_printf("[WQM] Manager started successfully\n");

	} else {
		debug_printf("[WQM] WARNING: already running\n");
		return -1;
	}

	return 0;
}

/**
 * Stop the work queue manager
 */
int WorkQueueManagerStop()
{
	if (!_wq_manager_should_exit.load()) {

		// Error: can't shutdown until all WorkItems are removed/stopped
		if (_wq_manager_running.load() && (_wq_manager_wqs_list->size() > 0)) {
			debug_printf("[WQM] ERROR: can't shutdown with active WQs\n");
			WorkQueueManagerStatus();
			return -1;
		}

		// First ask all WQs to stop
		if (_wq_manager_wqs_list != nullptr) {
			{
				LockGuard lg{_wq_manager_wqs_list->mutex()};

				// Ask all work queues (threads) to stop
				for (WorkQueue *wq : *_wq_manager_wqs_list) {
					wq->request_stop();
				}
			}

			// Wait until they're all stopped (empty list)
			while (_wq_manager_wqs_list->size() > 0) {
				vTaskDelay(pdMS_TO_TICKS(1));
			}

			delete _wq_manager_wqs_list;
			_wq_manager_wqs_list = nullptr;
		}

		_wq_manager_should_exit.store(true);

		if (_wq_manager_create_queue != nullptr) {
			// Push nullptr to wake the wq manager task
			_wq_manager_create_queue->push(nullptr);

			vTaskDelay(pdMS_TO_TICKS(10));

			delete _wq_manager_create_queue;
			_wq_manager_create_queue = nullptr;
		}

		debug_printf("[WQM] Manager stopped\n");

	} else {
		debug_printf("[WQM] WARNING: not running\n");
		return -1;
	}

	return 0;
}

/**
 * Print work queue manager status
 */
int WorkQueueManagerStatus()
{
	if (!_wq_manager_should_exit.load() && _wq_manager_running.load()) {

		const size_t num_wqs = _wq_manager_wqs_list->size();
		debug_printf("\n========================================\n");
		debug_printf("  Work Queue Manager Status\n");
		debug_printf("========================================\n");
		debug_printf("Work Queues: %u\n", (unsigned)num_wqs);

		LockGuard lg{_wq_manager_wqs_list->mutex()};
		size_t i = 0;

		for (WorkQueue *wq : *_wq_manager_wqs_list) {
			i++;
			const bool last_wq = (i >= num_wqs);

			if (!last_wq) {
				debug_printf("|__ %u) ", (unsigned)i);
			} else {
				debug_printf("\\__ %u) ", (unsigned)i);
			}

			wq->print_status(last_wq);
		}

		debug_printf("========================================\n");

	} else {
		debug_printf("[WQM] Not running\n");
	}

	return 0;
}

} // namespace px4

